<template>

    
    <div>
        <h2>图书管理</h2>
        <header>
            <p>添加</p>
            <span>编号：</span>  
            <input type="text" v-model="num">
            <span>名称：</span>
            <input type="text" v-model="name">
            <button @click="onSub()">提交</button>
            <hr>
            <span>图书数量:</span>
            {{ bookCount }}
            <hr>
            <table>
                <tr>
                    <th>编号</th>
                    <th>名称</th>
                    <th>时间</th>
                    <th>操作</th>
                </tr>
            </table>
        </header>
        <main>
            <ul>
                <li v-for="(book,num) in books" :key="num">
                    <table>
                        <tr>
                            <td>{{ book.num }}</td>
                            <td>{{ book.name }}</td>
                            <td>{{ book.date }}</td>
                            <td><a href="#" @click="onDel(num)">删除</a></td>
                        </tr>
                    </table>
                </li>
            </ul>
        </main>
    </div>
</template>

<script setup>
import { ref} from 'vue';
let books =ref([]);
const num = ref('');
const name = ref('');
let bookCount = ref(0);
function onSub(){
    if(num.value=="" || name.value==""){
        alert("编号或名称不能为空！");
        return;
    }
    for(let i=0; i<books.value.length; i++){
        if(num.value==books.value[i].num){
            alert("该编号已经存在！");
            return;
        }            
    }
    let time = new Date();
    let book = {num:num.value,name:name.value,date:time.toLocaleString()};
    //console.log(book);
    num.value="";
    name.value="";
    books.value.push(book);
    bookCount.value++;
}
const onDel = (n)=>{
    for(let i=0; i<books.value.length; i++){
        if(i==n){
            //console.log(n);
            books.value.splice(i,1);
        }
    }
    bookCount.value--;
}

</script>

<style scoped>
    div{text-align: center;}
    header{background-color: #f3dcab; width: 550px; margin: 0 auto; padding: 10px 0;}
    header p{text-align: left; font-weight: 600;margin:0 0 0 18px;}
    table tr :nth-child(1){width: 75px;}
    table tr :nth-child(2){width: 100px;}
    table tr :nth-child(3){width: 300px;}
    table tr :nth-child(4){width: 75px;}
    header span{margin: 0;}
    header input{width: 170px; margin-right: 10px;}
    main{background-color: #fff; width: 550px; margin: -20px auto -20px auto;}
    main ul li{list-style: none; margin-left: -40px;}
    main table{border: 2px dotted #f3dcab; border-top-color: #fff; padding: 5px 0;}
</style>